package codetop.microsoft.T468;

/**
 * @Author: 18362
 * @Create: 2022-08-19 8:40:48 星期五
 */
class Solution {
    public String validIPAddress(String queryIP) {
        if (queryIP.length() == 0)
            return "Neither";
        char a = queryIP.charAt(0), b = queryIP.charAt(queryIP.length()-1);
        if (a == '.' || a == ':' || b == '.' || b == ':')
            return "Neither";
        String[] ips = queryIP.split("\\.");
        if (ips.length == 4) {
            for (int i=0; i<ips.length; ++i) {
                if (!isValidIpv4(ips[i]))
                    return "Neither";
            }
            return "IPv4";
        }
        ips = queryIP.split(":");
        if (ips.length != 8)
            return "Neither";
        for (int i=0; i<ips.length; ++i) {
            if (!isValidIpv6(ips[i]))
                return "Neither";
        }
        return "IPv6";
    }

    private boolean isValidIpv4(String s) {
        if (s.length() == 0 || s.length() > 3)
            return false;
        if (s.length() == 1 && s.charAt(0) == '0')
            return true;
        int value = 0;
        for (int i=0; i<s.length(); ++i) {
            char c = s.charAt(i);
            if (c >= '0' && c <= '9') {
                if (value == 0 && c == '0')
                    return false;
                value = value * 10 + c - '0';
            } else {
                return false;
            }
        }
        if (value <= 255)
            return true;
        return false;
    }

    private boolean isValidIpv6(String s) {
        if (s.length() == 0 || s.length() > 4)
            return false;
        for (int i=0; i<s.length(); ++i) {
            char c = s.charAt(i);
            if (c >= 'g' && c <= 'z')
                return false;
            if (c >= 'G' && c <= 'Z')
                return false;
        }
        return true;
    }
}